import cv2

# 视频捕获对象
cap = cv2.VideoCapture(0)

# 定义视频编码器和创建VideoWriter对象
fourcc = cv2.VideoWriter_fourcc(*'XVID')  # 定义编码器
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

while (cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        # 将帧写入视频文件
        out.write(frame)
        # 显示帧
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# 释放VideoCapture和VideoWriter对象
cap.release()
out.release()
cv2.destroyAllWindows()
